package lucene.server.database.utils;


import java.lang.reflect.Type;
import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class DatabaseUtil {


    /**
     * 执行 SELECT 查询并将结果转换为 List<Map<String, Object>> 形式
     * @param sql SQL 查询语句
     * @return 查询结果的列表
     */
    public static List<Map<String, Object>> executeSelectToList(Connection conn,String sql) {
        List<Map<String, Object>> resultList = new ArrayList<>();
        Statement stmt = null;
        ResultSet rs = null;

        try {
            stmt = conn.createStatement();
            rs = stmt.executeQuery(sql);
            ResultSetMetaData metaData = rs.getMetaData();
            int columnCount = metaData.getColumnCount();

            while (rs.next()) {
                Map<String, Object> rowMap = new HashMap<>(columnCount);
                for (int i = 1; i <= columnCount; i++) {
                    rowMap.put(metaData.getColumnName(i), rs.getObject(i));
                }
                resultList.add(rowMap);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            close(rs, stmt);
        }

        return resultList;
    }
    private static Object getColumnValue(ResultSet rs, int columnIndex, int type, Type targetColumnType) throws SQLException {
        Object rawValue = null;
        switch (type) {
            case Types.TIMESTAMP:
                try{
                    rawValue = rs.getTimestamp(columnIndex);
                } catch (SQLException ignore){
                    // issue#776@Github
                    // 当数据库中日期为0000-00-00 00:00:00报错，转为null
                }
                break;
            case Types.TIME:
                rawValue = rs.getTime(columnIndex);
                break;
            default:
                rawValue = rs.getObject(columnIndex);
        }

        return rawValue;
    }

    public static void close(Object... objsToClose) {
        for (Object obj : objsToClose) {
            if (null != obj && obj instanceof AutoCloseable) {
                try {
                    ((AutoCloseable)obj).close();
                } catch (Exception e) {

                }
            }
        }
    }
}
